package com.atguigu.controller;

import com.atguigu.entity.UserFollow;
import com.atguigu.entity.UserInfo;
import com.atguigu.entity.vo.UserFollowVo;
import com.atguigu.result.Result;
import com.atguigu.service.UserFollowService;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/userFollow")
public class UserFollowController {

    @Reference
    private UserFollowService userFollowService;

    @ResponseBody
    @GetMapping("/auth/follow/{id}")
    public Result addFollow(@PathVariable Long id, HttpSession session){
        //通过表结构可以看出添加关注就是将用户ID和房源ID放入一张表中
        UserInfo userInfo = (UserInfo)session.getAttribute("existUser");
        Long userInfoId = userInfo.getId();
        UserFollow userFollow = new UserFollow();
        userFollow.setUserId(userInfoId);
        userFollow.setHouseId(id);
        userFollowService.insert(userFollow);
        return Result.ok();
    }

    @ResponseBody
    @GetMapping("/auth/cancelFollow/{id}")
    public Result cancelFollow(@PathVariable Long id,HttpSession session){
        UserInfo userInfo = (UserInfo)session.getAttribute("existUser");
        Long userInfoId = userInfo.getId();
        userFollowService.deleteByUserIdAndHouseId(userInfoId,id);
        return Result.ok();
    }

    @ResponseBody
    @GetMapping("/auth/list/{pageNum}/{pageSize}")
    public Result list(@PathVariable Integer pageNum, @PathVariable Integer pageSize,HttpSession session){
        UserInfo existUser = (UserInfo) session.getAttribute("existUser");
        Long id = existUser.getId();
        PageInfo<UserFollowVo> pageInfo = userFollowService.findByPage(pageNum,pageSize,id);
        return Result.ok(pageInfo);
    }

    @ResponseBody
    @GetMapping("/auth/cancelFollowById/{id}")
    public Result cancelFollowByKey(@PathVariable Long id){
        userFollowService.cancelFollowByKey(id);
        return Result.ok();
    }
}
